package com.huai.jt1078.handler.thread;

import com.huai.jt1078.utils.JedisUtil;
import com.huai.jt1078.utils.SessionManager;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author xingkong
 * @program jt1078
 * @description 心跳检测线程
 * @date 2021-09-15 11:43
 **/
@Slf4j
public class HeartbeatThread extends Thread{

    private final String tag;
    private final ScheduledExecutorService scheduledExecutorService;

    public HeartbeatThread(String tag) {
        this.tag = tag;
        this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    }

    @Override
    public void run() {
        // 创建延时定时线程 每十秒检测一次通道是否有人观看 若没有人看需要立即关闭通道
        this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
           @Override
           public void run() {
               log.info(" -------{}通道心跳检测-------", tag);
               // 判断当前是否还有人观看
               boolean exists = JedisUtil.exists(tag);
               if (exists){
                   return;
               }
               log.error("-------- {} 通道已经无人观看，立即关闭 -------",tag);
               try {
                   ChannelHandlerContext context = SessionManager.instance.getTagChannelMap().get(tag);
                   if (null != context){
                       context.close();
                   }
                   scheduledExecutorService.shutdown();
               } catch (Exception e) {
                   log.error("自己关闭通道失败");
                   e.printStackTrace();
               }

           }
        }, 10, 15, TimeUnit.SECONDS);
    }
}
